package com.ilxqx.framework.amqp.controller;

import com.ilxqx.framework.amqp.constant.RabbitMessageConstants;
import com.ilxqx.framework.amqp.entity.SysMessageLog;
import com.ilxqx.framework.amqp.enumeration.SysMessageLogStatusEnum;
import com.ilxqx.framework.amqp.form.search.SysMessageLogSearchForm;
import com.ilxqx.framework.amqp.service.SysMessageLogService;
import com.ilxqx.framework.system.controller.base.AbstractFrameworkController;
import com.ilxqx.framework.system.form.UpdateForm;
import com.ilxqx.framework.util.ResultUtils;
import com.ilxqx.framework.vo.ResultVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Optional;

/**
 * 系统消息日志控制器
 * @author venus
 */
@Api("系统消息日志控制器")
@RestController
@RequestMapping("/log/sys-message-log")
@Slf4j
public class SysMessageLogController extends AbstractFrameworkController<SysMessageLog, Long, SysMessageLogSearchForm, UpdateForm> {

	private final SysMessageLogService sysMessageLogService;

	@Autowired
	public SysMessageLogController(SysMessageLogService sysMessageLogService) {
		super(sysMessageLogService);
		this.sysMessageLogService = sysMessageLogService;
	}

	/**
	 * 重置重试次数
	 * @param messageId 消息ID
	 * @return 结果对象
	 */
	@ApiOperation("重置重试次数")
	@PutMapping("/reset")
	public ResultVO reset(@RequestParam Long messageId) {
		Optional<SysMessageLog> sysMessageLogOptional = this.sysMessageLogService.get(messageId);
		if (sysMessageLogOptional.isEmpty()) {
			return ResultUtils.failure("消息不存在");
		}
		SysMessageLog sysMessageLog = sysMessageLogOptional.get();
		if (sysMessageLog.getStatus().equals(SysMessageLogStatusEnum.SENDING_SUCCESS) || sysMessageLog.getTryCount() < RabbitMessageConstants.MAX_RETRY_COUNT) {
			return ResultUtils.failure("消息必须是失败状态且重试次数等于" + RabbitMessageConstants.MAX_RETRY_COUNT + "才可以重置");
		}
		sysMessageLog.setTryCount(0);
		this.sysMessageLogService.modify(sysMessageLog);
		return ResultUtils.success("重置成功");
	}

}
